package com.encryption.plugin.util;


import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @author liuzhiqiang
 */
public class ArrUtils {
    public static int getLength(Object array) {
        return array == null ? 0 : Array.getLength(array);
    }

    public static boolean isNotEmpty(int[] array) {
        return array != null && array.length != 0;
    }

    public static byte[] removeAll(byte[] array, int... indices) {
        return (byte[]) removeAll((Object) array, indices);
    }

    static Object removeAll(Object array, int... indices) {
        int length = getLength(array);
        int diff = 0;
        int end;
        int dest;
        if (isNotEmpty(indices)) {
            Arrays.sort(indices);
            int i = indices.length;
            end = length;

            while (true) {
                --i;
                if (i < 0) {
                    break;
                }

                dest = indices[i];
                if (dest < 0 || dest >= length) {
                    throw new IndexOutOfBoundsException("Index: " + dest + ", Length: " + length);
                }

                if (dest < end) {
                    ++diff;
                    end = dest;
                }
            }
        }

        Object result = Array.newInstance(array.getClass().getComponentType(), length - diff);
        if (diff < length) {
            end = length;
            dest = length - diff;

            for (int i = indices.length - 1; i >= 0; --i) {
                int index = indices[i];
                if (end - index > 1) {
                    int cp = end - index - 1;
                    dest -= cp;
                    System.arraycopy(array, index + 1, result, dest, cp);
                }

                end = index;
            }

            if (end > 0) {
                System.arraycopy(array, 0, result, 0, end);
            }
        }

        return result;
    }
}
